<template>
  <VZPanel title="重复发生问题TOP" simple iconText="mdi-chart-pie">
    <div style="margin:-16px">
      <v-card>
        <v-row>
          <v-col cols="2" sm="6" md="3">
            <v-menu
                    ref="menu"
                    v-model="menu"
                    :close-on-content-click="false"
                    :return-value.sync="startDate"
                    transition="scale-transition"
                    offset-y
                    min-width="auto"
            >
              <template v-slot:activator="{ on, attrs }">
                <v-text-field
                        v-model="startDate"
                        label="开始日期"
                        prepend-icon="mdi-calendar"
                        readonly
                        v-bind="attrs"
                        v-on="on"
                ></v-text-field>
              </template>
              <v-date-picker
                      v-model="startDate"
                      no-title
                      scrollable
                      locale = "zh-cn"
              >
                <v-spacer></v-spacer>
                <v-btn
                        text
                        color="primary"
                        @click="menu = false"
                >
                  取消
                </v-btn>
                <v-btn
                        text
                        color="primary"
                        @click="$refs.menu.save(startDate)"
                >
                  确定
                </v-btn>
              </v-date-picker>
            </v-menu>
          </v-col>
          <v-col cols="2" sm="6" md="3">
            <v-menu
                    ref="menu2"
                    v-model="menu2"
                    :close-on-content-click="false"
                    :return-value.sync="endDate"
                    transition="scale-transition"
                    offset-y
                    min-width="auto"
            >
              <template v-slot:activator="{ on, attrs }">
                <v-text-field
                        v-model="endDate"
                        label="结束日期"
                        prepend-icon="mdi-calendar"
                        readonly
                        v-bind="attrs"
                        v-on="on"
                ></v-text-field>
              </template>
              <v-date-picker
                      v-model="endDate"
                      no-title
                      scrollable
                      locale = "zh-cn"
              >
                <v-spacer></v-spacer>
                <v-btn
                        text
                        color="primary"
                        @click="menu2 = false"
                >
                  取消
                </v-btn>
                <v-btn
                        text
                        color="primary"
                        @click="$refs.menu2.save(endDate)"
                >
                  确定
                </v-btn>
              </v-date-picker>
            </v-menu>
          </v-col>
          <v-col cols="2" >
            <v-select
              v-model="plantCode"
              :items="plantItems"
              label="工厂"
              multiple
              chips
              item-text="text"
              return-object
            ></v-select>
          </v-col>
          <v-col cols="2" >
            <v-combobox  v-model="workshopCode" :items="workshopItems" label="车间"  ></v-combobox>
          </v-col>
          <v-col cols="2" >
            <v-combobox  v-model="departmentCode" :items="departmentItems" label="责任部门"  ></v-combobox>
          </v-col>
          <v-col cols="2">
            <v-select :items="problemTypeItems" label="问题类型" item-text="name" item-value="code" v-model="problemType" ></v-select>
          </v-col>
          <v-col cols="2" >
            <v-combobox  v-model="chargePersonCode" :items="chargePersonItems" label="责任人"  ></v-combobox>
          </v-col>
          <v-col cols="1" >
            <v-btn class="ma-1" outlined color="primary" @click="search_data"><v-icon >mdi-magnify</v-icon>查询</v-btn>
          </v-col>
          <v-col cols="2" >
            <v-btn class="ma-1" outlined color="primary" @click="reset"><v-icon >mdi-refresh</v-icon>重置</v-btn>
          </v-col>
        </v-row>
        <div ref="target" style="width:100%;height:450px"></div>
      </v-card>
    </div>
  </VZPanel>
</template>
<script>
  export default {
    data() {
      return {
        nameList:[],
        numList:[],
        startDate: null,
        endDate: null,
        menu: false,
        menu2: false,
        departmentCode:'',
        departmentItems:[],
        chargePersonCode:'',
        chargePersonItems:[],
        plantCode:[],
        plantItems:[],
        workshopCode:'',
        workshopItems:[],
        problemTypeItems:app.utils.getEntrys("QUALITY_PROBLEM_TYPE"),
        problemType:'',
        baseCode:''
      }
    },
    methods: {
      run() {
        this.chartTarget = this.chartTarget || this.$echarts.init(this.$refs.target)
        let option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend:{
            data:['问题数'],
            right: "center"
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            show: false,
            feature: {
              dataView: {
                readOnly: false
              },
              magicType: {
                type: ["line","stack"]
              },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: [
            {
              type: 'category',
              axisTick: {
                show:false
              },
              axisLabel: {
                rotate: 45, // 旋转45度
                interval: 0, // 显示所有标签
                formatter: function (value) {
                  return value.length > 10 ? value.substring(0, 10) + '...' : value; // 截断超过10个字符的标签
                }
              },
              data:this.nameList
            },
          ],
          yAxis: [
            {
              type: 'value',
              name: '数量',
              axisLabel: {
                formatter: '{value} 个'
              }
            }
          ],
          series: [
            {
              data: this.numList,
              name:'问题数',
              type: 'bar',
              barMaxWidth:40,
              tooltip: {
                valueFormatter: function (value) {
                  return value + '个';
                }
              },
              itemStyle:{
                normal:{
                  label:{
                    show:true,
                    position:'top',
                    textStyle:{
                      color: '#88aecc',
                      fontSize: 12
                    }
                  },
                  barBorderRadius:[5,5,0,0],
                  color: "#59b2ef",
                }
              }
            },
          ]
        }
        option && this.chartTarget.setOption(option)
      },
      search_data(){
        if (!this.startDate || !this.endDate) {
          this.$message.error("请选择开始日期和结束日期");
          return;
        }
        let _this = this;

        // 每次查询前动态构建SQL语句
        let dynamicSQL = "SELECT DEFECT_DESCRIPTION AS NAME, count( 1 ) AS num  FROM  tb_quality_problem WHERE MARK_FOR_DELETE = 0 AND DEFECT_DESCRIPTION IS NOT NULL";
        
        // 获取各个查询条件
        let chargePersonId = '';
        if(this.chargePersonCode != undefined && this.chargePersonCode != null && this.chargePersonCode != ''){
          chargePersonId = this.chargePersonCode.id;
          dynamicSQL += " AND CHARGE_PERSON_ID = '" + chargePersonId + "'";
        }
        
        let department_id = '';
        if(this.departmentCode != undefined && this.departmentCode != null && this.departmentCode != ''){
          department_id = this.departmentCode.id;
          dynamicSQL += " AND CHARGE_PERSON_DEPT_ID = '" + department_id + "'";
        }
        
        let plant_ids = [];
        if(this.plantCode != undefined && this.plantCode != null && this.plantCode.length > 0){
          plant_ids = this.plantCode.map(item => "'" + item.id + "'");
          dynamicSQL += " AND PLANT_ID IN (" + plant_ids.join(",") + ")";
        }
        
        let workshop_id = '';
        if(this.workshopCode != undefined && this.workshopCode != null && this.workshopCode != ''){
          workshop_id = this.workshopCode.id;
          dynamicSQL += " AND WORKSHOP_ID = '" + workshop_id + "'";
        }
        
        if(this.problemType != undefined && this.problemType != null && this.problemType != ''){
          dynamicSQL += " AND QUALITY_PROBLEM_TYPE = '" + this.problemType + "'";
        }
        
        // 添加日期条件
        dynamicSQL += " AND PROBLEM_HAPPEN_DATE <= '" + this.endDate + "'";
        dynamicSQL += " AND PROBLEM_HAPPEN_DATE >= '" + this.startDate + "'";
        
        // 添加基地条件
        if(this.baseCode != undefined && this.baseCode != null && this.baseCode != ''){
          dynamicSQL += " AND COMPANY_CODE = '" + this.baseCode + "'";
        }
        
        // 添加分组和排序
        dynamicSQL += " GROUP BY DEFECT_DESCRIPTION ORDER BY num DESC";
        
        console.log("动态SQL:", dynamicSQL);
        let params = {"SQL": dynamicSQL};
        
        console.log("查询参数:", {
          plantCode: plant_ids.join(','),
          workshopCode: workshop_id,
          departmentCode: department_id,
          chargePersonCode: chargePersonId,
          problemType: this.problemType,
          startDate: this.startDate,
          endDate: this.endDate
        });
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if(res.success){
              _this.nameList = [];
              _this.numList = [];
              console.log("查询返回数据:", res.rows);
              res.rows.forEach((item) => {
                // _this.nameList.push(app.utils.getEntryValue("RANK_LEVEL_TYPE", item.name));
                _this.nameList.push(item.name);
                _this.numList.push(item.num);
                /*item.problem_status_show = app.utils.getEntryValue("QUALITY_PROBLEM_STATUS", item.problem_status);
                item.process_status_show = app.utils.getEntryValue("PROBLEM_PROCESS_NODE_STATUS", item.process_status);
                item.problem_source = app.utils.getEntryValue("QUALITY_PROBLEM_SOURCE", item.problem_source);
                item.defect_type_show = app.utils.getEntryValue("PROBLEM_DEFECT_TYPE", item.defect_type);*/
              })
              _this.run();
            } else {
              console.error("查询失败:", res);
            }
          },
        })
      },
      // 获取工厂
      loadPlantData() {
        let _this = this;
        _this.plantItems = [];
        
        let plantSQL = "SELECT PLANT_ID id,PLANT_NAME name FROM tb_quality_problem WHERE PLANT_ID IS NOT NULL AND MARK_FOR_DELETE = 0 GROUP BY PLANT_ID";
        let params = {"SQL": plantSQL};
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let plantList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                plantList.push(map);
              })
              _this.plantItems = plantList;
            }
          },
        })
      },
      // 获取责任部门
      loadDepartmentData() {
        let _this = this;
        _this.departmentItems = [];
        
        let deptSQL = "SELECT CHARGE_PERSON_DEPT_ID id,CHARGE_PERSON_DEPT name FROM tb_quality_problem WHERE CHARGE_PERSON_DEPT_ID IS NOT NULL AND MARK_FOR_DELETE = 0 GROUP BY CHARGE_PERSON_DEPT_ID";
        let params = {"SQL": deptSQL};
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let departmentList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                departmentList.push(map);
              })
              _this.departmentItems = departmentList;
            }
          },
        })
      },
      // 获取责任人
      loadChargePersonData() {
        let _this = this;
        _this.chargePersonItems = [];
        
        let personSQL = "SELECT CHARGE_PERSON_ID id,CHARGE_PERSON_NAME name FROM tb_quality_problem WHERE CHARGE_PERSON_ID IS NOT NULL AND MARK_FOR_DELETE = 0 GROUP BY CHARGE_PERSON_ID";
        let params = {"SQL": personSQL};
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let chargePersonList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                chargePersonList.push(map);
              })
              _this.chargePersonItems = chargePersonList;
            }
          },
        })
      },
      // 获取车间
      loadWorkshopData() {
        let _this = this;
        _this.workshopItems = [];
        
        // 动态构建车间查询语句
        let workshopSQL = "SELECT WORKSHOP_ID id,WORKSHOP_NAME name FROM tb_quality_problem WHERE WORKSHOP_ID IS NOT NULL AND MARK_FOR_DELETE = 0";
        
        let plant_ids = [];
        if(this.plantCode != undefined && this.plantCode != null && this.plantCode.length > 0){
            plant_ids = this.plantCode.map(item => "'" + item.id + "'");
            workshopSQL += " AND PLANT_ID IN (" + plant_ids.join(",") + ")";
        }
        
        workshopSQL += " GROUP BY WORKSHOP_ID";
        
        let params = {"SQL": workshopSQL};
        console.log("车间查询SQL:", workshopSQL);
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let workshopList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                workshopList.push(map);
              })
              _this.workshopItems = workshopList;
            }
          },
        })
      },
      reset(){
        let now = new Date();
        let start = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        this.startDate = start.toISOString().split('T')[0];
        this.endDate = now.toISOString().split('T')[0];

        this.plantCode = [];
        this.workshopCode = '';
        this.departmentCode = '';
        this.chargePersonCode = '';
        this.problemType = '';

        this.search_data();
      },
      load_user(){
        let _this = this;
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CURRENT_USER_INFO",
          params: {
            //functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
                            console.log(res.rows);
                            let role_code = res.rows[0].role_code;
                            let roleCodes = role_code.split(',');
                            if(roleCodes.includes('admin') || roleCodes.includes('qms_admin')){
                                
                            }else{
                                _this.baseCode = res.rows[0].base_code;
                            }
                        }
                        _this.search_data();
          },
        })
      },
    },
      watch:{
        "plantCode": {
          handler(newVal) {
            this.loadWorkshopData();
            console.log(this.plantCode);
          },
          deep: true
        },
  },
    created() {
      let now = new Date();
      let start = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      this.startDate = start.toISOString().split('T')[0];
      this.endDate = now.toISOString().split('T')[0];
      // this.generateByModel()
    },
    mounted() {
      this.load_user();
      //this.search_data();
      this.loadChargePersonData();
      this.loadDepartmentData();
      this.loadWorkshopData();
      this.loadPlantData();
      window.onresize = () => {
        this.chartTarget.resize();
      }
    },
  }
</script>
